import Big from 'big.js'

let wallet: string = ''
let web3Js: any = undefined
/** 获取Web3
 * @param id
 */
export const getWeb3 = async (id?: string | number) => {
  const ethereum = (window as any).ethereum
  await ethereum.request({ method: 'eth_requestAccounts' })
  if (!web3Js) web3Js = new Web3(ethereum)
  const chain = await web3Js.eth.net.getId()
  const chainId = id || 56
  if (Number(chain) !== Number(chainId)) {
    await ethereum.request({
      method: 'wallet_switchEthereumChain',
      params: [{ chainId: `0x${chainId.toString(16)}` }]
    })
  }
  return web3Js
}

/** 获取钱包
 * @param isSignature
 */
export const getWallet = async (isSignature = false): Promise<string> => {
  if (wallet) return wallet
  const web3 = await getWeb3()
  const addressList = await web3.eth.getAccounts()
  wallet = addressList[0]
  if (isSignature) {
    const key = await web3.eth.personal.sign(web3.utils.utf8ToHex(wallet), wallet, '')
    if (!key || !wallet) return Promise.reject()
  }
  return wallet
}

export const getContract = async (abi: any, address: string) => {
  const web3 = await getWeb3()
  return new web3.eth.Contract(abi, address)
}

type ChainParams = {
  chainId: number | `0x${string}`
  chainName: string
  decimals: number
  iconUrls: string
  rpcUrls: string
  blockExplorerUrls: string
}
/** 添加链 默认值为 3T链
 * @param data
 */
export const addChainList = async (data: ChainParams = {
  chainId: 81188,
  chainName: '3T',
  decimals: 18,
  iconUrls: 'https://ai.metatel.com.cn/static/img/RS_logo.97a6569b.png',
  rpcUrls: 'https://mainnet.3tlab.xyz:8443',
  blockExplorerUrls: 'https://scan.3tlab.xyz'
}): Promise<void> => {
  await (window.ethereum as any).request({
    method: 'wallet_addEthereumChain',
    params: [
      {
        chainId: typeof data.chainId === 'number' ? `0x${data.chainId.toString(16)}` : data.chainId,
        chainName: data.chainName,
        nativeCurrency: {
          name: data.chainName,
          symbol: data.chainName,
          decimals: data.decimals
        },
        iconUrls: [data.iconUrls],
        rpcUrls: [data.rpcUrls], // 节点
        blockExplorerUrls: [data.blockExplorerUrls]
      }
    ]
  })
}

/** 获取gas余额
 * @param wallet 钱包地址
 */
export const getGasBalance = async (wallet: string): Promise<string> => {
  const web3 = await getWeb3()
  const balance = await web3.eth.getBalance(wallet)
  return new Big(balance).div(10 ** 18).toFixed()
}
